package boun.center;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class TweetComparator implements Comparator<Tweet>{
    
    @Override
    public int compare(Tweet o1, Tweet o2) {
        // The newer comes earlier
        return o2.getCreationDate().compareTo(o1.getCreationDate());
    }
}

public class TwitterFetcher {
    private static final int MAX_TWEETS = 5;
    // https://dev.twitter.com/docs/api/1/get/statuses/user_timeline
    private static final String SOURCE_URL = "https://api.twitter.com/1/statuses/user_timeline.json?" +
    		                                 "include_entities=false&" + // No hashtags', links', etc. metadata
    		                                 "include_rts=true&" + // Include retweets
    		                                 "trim_user=true&" + // No detailed user info
    		                                 "screen_name=bogazici_un&" +
    		                                 "count=" + MAX_TWEETS;

    public static ArrayList<Tweet> fetchTweets() throws IOException, ParseException, JSONException {
        String webContent = WebDownloader.fetchWebContent(SOURCE_URL);
        JSONArray twitterResponseJson = new JSONArray(webContent);
        
        ArrayList<Tweet> tweets = new ArrayList<Tweet>();
        for (int i = 0; i < twitterResponseJson.length(); ++i) {
            JSONObject json = twitterResponseJson.getJSONObject(i);
            tweets.add(new Tweet(json.getString("text"), json.getString("created_at")));
        }
        
        Collections.sort(tweets, new TweetComparator());
        return tweets;
    }
}
